package com.gxuwz.attend.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

//@WebFilter(filterName = "AuthFilter", urlPatterns = {"/*"})
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取会话
        HttpSession session = httpRequest.getSession(false);

        // 检查会话中是否存在登录用户信息
        boolean loggedIn = (session != null && session.getAttribute("currentUser") != null);

        // 获取请求的 URI
        String requestURI = httpRequest.getRequestURI();
        String loginURI = httpRequest.getContextPath() + "/login.jsp"; // 登录页面的 URI

        // 允许访问登录页面和其他登录相关请求
        if (requestURI.equals(loginURI) || requestURI.equals(httpRequest.getContextPath() + "/login")) {
            chain.doFilter(request, response);
        } else {
            // 检查登录状态
            if (!loggedIn) {
                // 用户未登录，重定向到登录页面，并传递提示信息

                String errorMessage = "请登录";
                String encodedMessage = URLEncoder.encode(errorMessage, StandardCharsets.UTF_8.toString());
                httpResponse.sendRedirect(loginURI + "?error=" + encodedMessage);
            } else {
                // 已登录，继续处理请求
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化代码（如果需要）
    }

    @Override
    public void destroy() {
        // 销毁代码（如果需要）
    }
}
